package com.goodomen.garbage.web.web.controller.back.system;

import com.alibaba.fastjson.JSON;
import com.goodomen.garbage.common.persistence.model.system.SysAdmin;
import com.goodomen.garbage.common.persistence.model.system.SysPermission;
import com.goodomen.garbage.common.persistence.model.system.SysRole;
import com.goodomen.garbage.common.utils.BitMap;
import com.goodomen.garbage.web.constant.ResponseCodeEnum;
import com.goodomen.garbage.web.dto.PermissionDto;
import com.goodomen.garbage.web.dto.response.ResponseDto;
import com.goodomen.garbage.web.service.system.SysAdminService;
import com.goodomen.garbage.web.service.system.SysPermissionService;
import com.goodomen.garbage.web.service.system.SysRoleService;
import com.goodomen.garbage.web.util.JwtUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 后台登录
 *
 * @author : Zhao Da
 * @since : 2019/4/28 14:45
 */
@RestController
@RequestMapping("/back/login")
public class BackLoginController {

    @Autowired
    private SysAdminService backUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysPermissionService sysPermissionService;
    @Autowired
    private JwtUtil jwtUtil;

    @CrossOrigin(origins = "*", allowedHeaders = "Authorization,loginResult,Access-Control-Allow-Origin, Content-Type,accept")
    @ApiOperation(value = "（后台）用户登录", notes = "后台登录。")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "adminName", value = "用户名", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "password", value = "密码", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "authCode", value = "动态校验码", dataType = "string")
    })
    @RequestMapping(value = "/", method = RequestMethod.HEAD)
    public ResponseDto<String> login(HttpServletRequest request,
                                     HttpServletResponse response,
                                     @RequestParam(value = "adminName") String adminName,
                                     @RequestParam(value = "password") String password,
                                     @RequestParam(value = "authCode", required = false) Long authCode) {
        SysAdmin backUser = backUserService.login(request, adminName, password, authCode);
        if ((backUser != null && backUser.getRoleId() == null) || backUser == null) {
            response.addHeader("Authorization", "Bearer ");
            switch (backUser.getRemark()) {
                case "用户名" :
                    response.addHeader("loginResult", "1");
                    break;
                case "密码":
                    response.addHeader("loginResult", "2");
                    break;
                case "授权码":
                    response.addHeader("loginResult", "3");
                    break;
                default:
                    response.addHeader("loginResult", "4");
                    break;
            }
            return new ResponseDto<>(ResponseCodeEnum.FAILURE.getCode(), backUser.getRemark());
        }
        SysRole sysRole = sysRoleService.findPermissionByRoleId(backUser.getRoleId());
        SysPermission sysPermission = sysPermissionService.getMaxPermission();
        byte[] bytes = null;
        if (sysRole != null && sysPermission != null) {
            BitMap bitMap = new BitMap();
            bytes = bitMap.getPermission(sysRole.getPermissions(), sysPermission);
        }
        PermissionDto permissionDto = new PermissionDto();
        permissionDto.setBytes(bytes);
        ResponseDto<String> responseDto = new ResponseDto<>(ResponseCodeEnum.SUCCESS);
        response.addHeader("loginResult", "0");
        response.addHeader("Authorization", "Bearer " + jwtUtil.createTokenWithClaim(backUser.getUserName(),
                String.valueOf(backUser.getRoleId()), backUser.getRoleName(), JSON.toJSONString(permissionDto)));
        responseDto.setData("");
        return responseDto;
    }
}
